package zhan.interceptor;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import zhan.annotation.RzAnnotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 日志拦截器
 *
 * @author zhan
 * @date 2018-12-13 10:09
 */
public class RzIntercepter implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
//        //如果不是映射（添加）到方法则直接通过
//        if (!(handler instanceof HandlerMethod)) {
//            return true;
//        }
//
//        HandlerMethod handlerMethod = (HandlerMethod) handler;      //将处理转换成处理方法类型
//        Method method = handlerMethod.getMethod();                  //获取方法名称
//        System.out.println("方法名："+method);
//        RzAnnotation rzAnnotation = method.getAnnotation(RzAnnotation.class);
//        if (rzAnnotation != null) {
//            //输出日志的操作内容
//            String cznr = rzAnnotation.cznr();
//            System.out.println("##preHandle方法###本次的操作内容--------->" + cznr);
//        }
        return true;

    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {

        HandlerMethod handlerMethod = null;
        //如果不是映射（添加）到方法则直接通过
        if (handler instanceof HandlerMethod) {
            handlerMethod = (HandlerMethod) handler;      //将处理转换成处理方法类型
            Method method = handlerMethod.getMethod();                  //获取方法名称
            System.out.println("方法名："+method);
        }

        RzAnnotation rzAnnotation = handlerMethod.getMethodAnnotation(RzAnnotation.class);
        if (rzAnnotation != null) {
            //输出日志的操作内容
            String cznr = rzAnnotation.cznr();
            System.out.println("##postHandle方法###本次的操作内容--------->" + cznr);
        }

//
//        Class<?> aClass = handler.getClass();
//        RzAnnotation annotation = aClass.getAnnotation(RzAnnotation.class);   //获取的是空，不是到为啥
//        if (annotation != null) {
//            //输出日志的操作内容
//            String cznr = annotation.cznr();
//            System.out.println("#####本次的操作内容--------->" + cznr);
//        }

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {

    }
}
